package com.xp.framework;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author:xuecx
 * @descript:<p>解码器实现</p>
 * @date:2019/4/29
 */
public class NettyDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass;
    private MySerializer serializer;

    public NettyDecoder(Class<?> genericClass, MySerializer serializer) {
        this.genericClass = genericClass;
        this.serializer = serializer;
    }

    /**
     * 解码器实现
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }

        byteBuf.markReaderIndex();
        // 读取消息长度
        int dataLength = byteBuf.readInt();

        if (dataLength < 0) {
            channelHandlerContext.close();
        }

        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }

        try {
            byte[] data = new byte[dataLength];
            byteBuf.readBytes(data);
            Object object = serializer.deserialize(data, genericClass);
            list.add(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
